package neo.tetris.rpc.service;

import java.util.ArrayList;
import java.util.List;

import neo.sourceEngine.network.rpc.service.annotation.RpcService;
import neo.sourceEngine.network.rpc.service.annotation.RpcServiceParameter;
import neo.tetris.bean.model.World;
import neo.tetris.bean.model.battle.BattlePlayer;
import neo.tetris.rpc.message.MessageImpl;
import neo.tetris.rpc.session.SessionModel;

import org.springframework.stereotype.Service;

@Service
public class BattleService {
	@RpcService
	public void matchAuto(SessionModel session) {
		// 自动匹配
		World.instance.matchingSessions.add(session);
		session.write(MessageImpl.battleMessage.battleMatching());
	}
	
	@RpcService
	public void surrender(SessionModel session) {
		List<BattlePlayer> continuePlayers = new ArrayList<BattlePlayer>();
		for (BattlePlayer player : session.getPlayer().battle.players) {
			if (!player.surrender)
				continuePlayers.add(player);
		}
		if (continuePlayers.size() == 1) {
			// ignore
		} else {
			session.getPlayer().surrender = true;
			continuePlayers = new ArrayList<BattlePlayer>();
			for (BattlePlayer player : session.getPlayer().battle.players) {
				if (!player.surrender)
					continuePlayers.add(player);
			}
			if (continuePlayers.size() == 1)
				session.getPlayer().battle.observer.write(MessageImpl.battleMessage.battleEnd((short) continuePlayers.get(0).index));
		}
	}

	@RpcService(desc = "同步状态给所有人")
	public void stateSynchronize(SessionModel session,
			@RpcServiceParameter(name = "state") String state) {
		session.getPlayer().battle.observer.write(MessageImpl.battleMessage.stateSynchronize(session.getPlayer().index, state));
	}
	
	@RpcService(desc = "")
	public void addDifficult(SessionModel session,
			@RpcServiceParameter(name = "line") int line) {
		session.getPlayer().battle.observer.write(MessageImpl.battleMessage.addDifficult(session.getPlayer().index));
	}
}
